<template>
	<view class="index home-bg">
		<u-sticky offset-top="0" h5-nav-height="0" bg-color="transparent">
			<u-navbar :border-bottom="false" :is-fixed="false" custom-class="home-bg" :background="navBackground"
				:is-back="false">
				<view class="row logo-wrap flex1">
					{{day}}
				</view>
			</u-navbar>
			<view class="sticky-nav-footer">
				<view class="sticky-line"></view>
			</view>
		</u-sticky>
		<view class="contain">
			<view class="tips-wrap">
				<view class="tips">
					<u-notice-bar :speed="80" type="warning" color="#727272" bg-color="#F1F1F1" :list="tipsData">
					</u-notice-bar>
				</view>
			</view>
			<view class="address-wrap row-between">
				<navigator hover-class="none" url="/pages/user_address/user_address?type=1">
					<address-item :address="address"></address-item>
				</navigator>
				<!-- <view class="address row-between" @tap="goPage('/pages/user_address/user_address')">
					<u-icon class="map-icon" name="map"></u-icon>
					<view>百通科技园1号楼</view>
					<u-icon class="map-icon map-icon1" name="arrow-right"></u-icon>
				</view> -->
				<view class="distance" v-show="address.distance">距离您{{address.distance}}</view>
			</view>
			<!-- 明日菜单 -->
			<view class="goods">
				<view class="goods-title row">
					<text class="line"></text>
					<view class="row">
						<text class="bold lg">菜单</text>
						<text class="bold lg" style="margin:0 20rpx;">{{menuDay}}</text>
					</view>
				</view>
				<goods-list v-if="goodsList.length" :list="goodsList" @setOrderList="setOrderList"></goods-list>
				<loading-footer :status="status"></loading-footer>
			</view>
		</view>
		<view class="total-wrap row-between">
			<view class="row">合计:¥ <text class="amount"> {{totalPrice}}</text></view>
			<u-button size="medium" type="warning" shape="circle" @click="onConfirmOrder()">下单</u-button>
		</view>
	</view>
</template>

<script>
	import {
		mapGetters,
		mapActions
	} from 'vuex'
	import {
		getHome,
		getMenu,
		getBestList
	} from '@/api/store';
	import {
		loadingType
	} from '@/utils/type'
	import {
		isLocation
	} from '@/utils/getLocation'
	import {
		loadingFun,
		menuJump,
		arraySlice,
		setTabbar,
		getRect
	} from '@/utils/tools'
	import {
		toLogin
	} from '@/utils/login'
	import Cache from '@/utils/cache'
	import {
		getRegisterCoupon
	} from '@/api/app'
	import {
		getIndexAddress
	} from '@/api/user'

	const app = getApp()
	export default {
		data() {
			// Cache.remove('TOKEN')
			let {
				value: {
					notice
				}
			} = JSON.parse(uni.getStorageSync('_CONFIG'))
			const date = new Date()
			return {
				page: 1,
				status: loadingType.LOADING,
				lnglat: {},
				goodsList: [],
				orderList: {},
				totalPrice: 0,
				actualPrice: 0,
				address: {
					// contact: 'ssssssssssss'
				},
				tipsData: [
					notice
				],
				menuDay: '',
				day: `${date.getMonth() + 1}月${date.getDate()}日 | 星期${['天','一','二','三','四','五','六'][date.getDay()]}`
			}
		},
		async onLoad(options) {
			setTabbar()
			this.getBestListFun()

		},
		async onShow(options) {
			const isConfirm = uni.getStorageSync('_isConfirmOrder')
			console.log('-------_isConfirmOrder------', isConfirm)
			/* const pages = getCurrentPages();
			const curPage = pages[pages.length - 1]; */

			if (isConfirm) {
				this.orderList = {}
				this.totalPrice = 0
				this.page = 1
				this.goodsList = []
				this.status = loadingType.LOADING
				this.getBestListFun()
				uni.removeStorage({
					key: "_isConfirmOrder"
				})
			}
			/* this.$nextTick(function() {
				getRect('.index').then((res) => {
					if (res.top == 0) {
						this.navBg = 0
					}
				})
			}) */
			isLocation((lnglat) => {
				this.lnglat = lnglat
				this.getIndexAddressFun()
			})
		},
		onHide() {
			// #ifdef H5
			this.enable = false
			// #endif
		},
		onReachBottom() {
			this.getBestListFun()
		},
		onPullDownRefresh() {
			this.goodsList = []
			this.page = 1
			this.totalPrice = 0
			this.orderList = {}
			this.status = loadingType.LOADING
			this.getBestListFun()
			this.getIndexAddressFun()
		},
		onShareAppMessage() {
			const shareInfo = Cache.get('shareInfo')
			return {
				title: shareInfo.mnp_share_title,
				imageUrl: shareInfo.imageUrl,
				path: "pages/launch_page/launch_page?invite_code=" + this.inviteCode
			};
		},
		onPageScroll(e) {
			const top = uni.upx2px(100)
			const {
				scrollTop
			} = e
			if (!this.enable) return
			let percent = scrollTop / top
			this.navBg = percent > 1 ? 1 : percent
		},
		methods: {
			...mapActions(['getCartNum']),
			async onConfirmOrder() {
				// 数量小于0的菜单排除
				const orderList = Object.values(this.orderList).filter(({
					quantity
				}) => quantity > 0)
				if (!this.address.addressId) {
					this.$toast({
						title: '请先选择收获地址',
						endtime: 10 * 1000
					})
				} else if (orderList.length) {
					const data = encodeURIComponent(JSON.stringify({
						menus: orderList,
						totalPrice: this.totalPrice,
						actualPrice: this.actualPrice,
						type: 'cart',
						addressId: this.address.addressId
					}))
					const url = `/pages/confirm_order/confirm_order?data=${data}`;
					this.goPage(url)
				} else {
					this.$toast({
						title: '您未选择菜品'
					})
				}
			},
			async getBestListFun() {
				let {
					page,
					goodsList,
					status
				} = this
				const data = await loadingFun(getBestList, page, goodsList, status)
				if (!data) return
				console.log('this.page = data.page---------', this.page, data.page, page)
				this.page = data.page
				this.goodsList = data.dataList
				this.status = data.status
			},
			async getIndexAddressFun() {
				if (this.lnglat.latitude && this.lnglat.longitude) {
					const addressId = Cache.get('_address_id') || ''
					getIndexAddress({
						...this.lnglat,
						addressId
					}).then(({
						code,
						data
					}) => {
						if (code === 200) {
							if (data.distance) {
								data.distance = data.distance > 1000 ? `${data.distance/1000}千米` :
									`${data.distance}米`
							}
							this.address = data
							const day = new Date(this.address.day)
							this.menuDay = `(${day.getMonth() + 1}月${day.getDate()}日·${this.address.week})`
						}
					}).catch((err) => {
						console.log('getIndexAddress----err---------', err)
					})
				}
			},
			setOrderList(data) {
				this.orderList[data.id] = data
				let total = 0
				let price = 0
				// 计算总价
				Object.entries(this.orderList).forEach(([id, info]) => {
					// total = (total * 10000 + info.total * 10000) / 10000
					total = parseFloat((total + info.total).toFixed(2))
					price = parseFloat((price + info.actualPrice).toFixed(2))
				})
				this.totalPrice = total
				this.actualPrice = price
			},
			goPage(url) {
				if (!this.isLogin) return toLogin()
				uni.navigateTo({
					url,
					fail(err) {}
				})
			},

		},
		computed: {
			...mapGetters(["cartNum", "inviteCode", "appConfig"]),
			navBackground() {
				return {
					'background-color': `#FFCC46`
				}
			},
			seting() {
				const {
					index_setting
				} = this.appConfig
				return index_setting
			}
		}
	}
</script>

<style lang="scss">
	.index {

		background-size: 100% auto;
		background-color: #FFCC46;

		.logo-wrap {
			position: absolute;
			margin-left: 20rpx;
			font-size: 32rpx;
			font-family: PingFangSC-Medium, PingFang SC;
			font-weight: 500;
			color: #1F1F1F;
			line-height: 44rpx;

			.logo {
				width: auto;
				height: 52rpx;
			}
		}

		.contain {
			background-color: #fff;

			.tips-wrap {
				.tips {
					padding: 32rpx 24rpx;
					border-radius: 32rpx 32rpx 0 0;
					// background-color: #fff;

					.u-type-warning-light-bg {
						border-radius: 40rpx;
						/* background-color: #F1F1F1;
						.u-type-warning,
						.uicon-volume-fill {
							color: #727272;
						} */
					}
				}
			}

			.address-wrap {
				padding-right: 38rpx;
				color: #1E1E1E;
				font-size: 28rpx;

				.distance {
					color: #bbb;
					font-size: 24rpx;
					font-family: PingFangSC-Regular, PingFang SC;
					font-weight: 400;
					color: #727272;
				}
			}

			.goods {
				.goods-title {
					height: 80rpx;
					font-size: 32rpx;
					font-family: PingFangSC-Semibold, PingFang SC;
					font-weight: 600;
					color: #FF8F00;
					line-height: 44rpx;

					.line {
						margin: 0 22rpx 0 38rpx;
						width: 8rpx;
						height: 28rpx;
						background-color: #FFCC46;
						border-radius: 4rpx;
						color: #FFCC46;
					}

				}
			}
		}

		.total-wrap {
			position: fixed;
			bottom: 0;
			left: 0;
			z-index: 9;
			padding: 0 20rpx 0 50rpx;
			width: 100%;
			height: 46px;
			font-size: 26rpx;
			background-color: #FFF3E4;
			font-family: PingFangSC-Semibold, PingFang SC;

			.row {
				font-size: 28rpx;
				font-weight: 600;
				color: #727272;
				line-height: 40rpx;
			}

			.amount {
				margin-left: 14rpx;
				font-size: 48rpx;
				font-weight: 600;
				color: #FF6600;
				line-height: 66rpx;
			}

			.u-btn {
				font-size: 32rpx;
				font-weight: 500;
			}
		}
	}
</style>
